/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.data.db;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import edu.cmu.lti.sepia.infra.topic.model.Nugget;
import edu.cmu.lti.sepia.infra.topic.model.Vote;

/**
 * 
 * Manages answer nugget voting result object in a DB.
 * 
 * @see Vote
 * @author Hideki Shima
 *
 */
public class VoteDAO {
		
	public static void loadVotes( SQL sql, String table, int topicId, List<Nugget> nuggets )
		throws SQLException {
		//init -- need to be String key to avoid int vs Integer mismatch
		Map<String,Nugget> nuggetMap = new HashMap<String,Nugget>(nuggets.size());
		for ( Nugget n : nuggets ) {
			n.setVotes( new ArrayList<Vote>() );
			nuggetMap.put(n.getNuggetId()+"", n);
		}
		
		String query = Query.generate( Query.LOAD_VOTES, table );

		PreparedStatement ps = sql.getConnection().prepareStatement(query);
		ResultSet rs = null;
	
		ps.setInt(1, topicId);
		rs = sql.executeSelect(ps);
		while ( rs.next() ) {
			Vote v = rsToObject(rs);
			//nuggetMap.get( v.getNuggetId() ).getVotes().add( v );
			Nugget n = nuggetMap.get( v.getNuggetId()+"" );
			if ( n.getVotes()==null ) n.setVotes( new ArrayList<Vote>() );
			List<Vote> votes = n.getVotes();
			votes.add( v );
		}
		rs.close();
		ps.close();
	}
	
	public static void updateVotes( SQL sql, String table, List<Vote> votes ) throws SQLException {
		if (votes==null) return;
			
		String query = Query.generate( Query.UPDATE_VOTES, table );
		
		PreparedStatement ps = sql.getConnection().prepareStatement(query);
		for ( Vote v : votes ) {
			ps.setInt(1, v.getNuggetId());
			ps.setInt(2, v.getUserId());
			ps.setInt(3, v.isVoted()?1:0);
			ps.setInt(4, v.isVoted()?1:0);
			ps.addBatch();
		}
		sql.executeBatch(ps);
		ps.close();
	}
	
	private static Vote rsToObject( ResultSet rs ) throws SQLException {
		Vote vote = new Vote( rs.getInt(1), rs.getInt(2), rs.getInt(3)==1 );
		return vote;
	}
	
  public static JSONArray convertVotes( List<Vote> votes ) throws JSONException {
    JSONArray jsonArray = new JSONArray();
    if ( votes!=null ) {
      int total = 0;
      for ( Vote v : votes ) {
        JSONObject j = new JSONObject();
        j.put("userId", v.getUserId());
        j.put("isVoted", (v.isVoted()?1:0));
        //sb.append( "'nuggetId': " + v.getNuggetId() + ", " );
        total += v.isVoted()?1:0;
        jsonArray.put(j);
      }
      //work around
      JSONObject j = new JSONObject("{'userId': '0', 'isVoted': '"+total+"' } ");
      jsonArray.put(j);
    }
    return jsonArray;
  }
}
